﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialManagements
{
    /// <summary>
    /// 物料类别添加Handler
    /// </summary>
    public class CreateMaterialCategoryHandler : IRequestHandler<CreateMaterialCategoryCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料管理表仓储
        /// </summary>
        public readonly IBaseRepository<MaterialCategory> materialCategoryrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateMaterialCategoryHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="materialCategoryrepository"></param>
        /// <param name="logger"></param>
        public CreateMaterialCategoryHandler(IMapper mapper, IBaseRepository<MaterialCategory> materialCategoryrepository, ILogger<CreateMaterialCategoryHandler> logger)
        {
            this.mapper = mapper;
            this.materialCategoryrepository = materialCategoryrepository;
            this.logger = logger;
        }
        /// <summary>
        /// 物料类别
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(CreateMaterialCategoryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //查询部门信息是否存在
                var query =await (await materialCategoryrepository.GetAll()).Where(d => d.MaterialCategoryName== request.MaterialCategoryName).CountAsync(); ;
                if (query > 0)
                {
                    result.Msg = "物料类别名称已存在,请重新输入";
                }
                else
                {
                    //将条件转换成类
                    MaterialCategory materialCategory = mapper.Map<MaterialCategory>(request);
                    //添加数据
                    var res = await materialCategoryrepository.Add(materialCategory);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "物料类别添加成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "物料类别添加失败" + ex.Message;
                logger.LogError("物料类别添加失败" + ex.Message);
            }
            return result;
        }
    }
}
